package cn.wyl.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {

    //根据返回字符串  决定当前自己定义过滤器是什么类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//return "pre";
    }

    //同种类型过滤器的执行顺序
    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //2.获取url uri
        String uri = request.getRequestURI();
        System.out.println(request.getRequestURI());
        //直接放行的逻辑
        if (uri.endsWith("/login")||uri.endsWith("/reg")||uri.contains("/static/")){
            return  false;
        }
        //执行下面的run（）
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        //2.获取请求头中的 token
        String token = request.getHeader("token");

        //3.如果没有token，登录检查失败 ，
        if(token==null||token.length()==0){
            //3.1.返回登录检查失败的错误信息 :{ success:false, message:"登录检查失败，请重新登录"}
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("success" , false);
            resultMap.put("message" , "登录检查失败，请重新登录");
            //中文编码
            response.setContentType("application/json;charset=UTF-8");
            //把map转成json字符串，写到浏览器
            String resultJsonString = JSON.toJSONString(resultMap);

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            try {
                response.getWriter().print(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        //这里的返回结果没有任何意义，不用管
        return null;
    }
}
